﻿/*
 * 独立的上传文件页面。 2009-5-11
 * 可用于弹出窗口上传文件。
 * 
 * 
 * 
 * **/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Brettle.Web.NeatUpload;
using System.Collections.Generic;
using System.IO;
using EQT.Model;
using EQT.Dal;

public partial class uploadfile2 : System.Web.UI.Page
{
    private DaTfiles datfile = DevFuture.Common.WorkContext.AppCtx.GetObject("DaTfiles") as DaTfiles;
    private DaContract dacontract = DevFuture.Common.WorkContext.AppCtx.GetObject("DaContract") as DaContract;
    private DaSampleParameter dasp = DevFuture.Common.WorkContext.AppCtx.GetObject("DaSampleParameter") as DaSampleParameter;
    private DaSampleKept daSample = DevFuture.Common.WorkContext.AppCtx.GetObject("DaSampleKept") as DaSampleKept;
    private DaNotice daNotice = DevFuture.Common.WorkContext.AppCtx.GetObject("DaNotice") as DaNotice;
    private DaTestCatalog daCatalog = DevFuture.Common.WorkContext.AppCtx.GetObject("DaTestCatalog") as DaTestCatalog;
    private DaTestItem daItem = DevFuture.Common.WorkContext.AppCtx.GetObject("DaTestItem") as DaTestItem;
    private DaFileTemplate daTemplate = DevFuture.Common.WorkContext.AppCtx.GetObject("DaFileTemplate") as DaFileTemplate;

    
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!Page.IsPostBack)
        {
            string m = Request.QueryString["m"];
            //if (!String.IsNullOrEmpty(m) && m.Trim().Equals("1")) //多文件
            //{
            //    multiFileId2.Enabled = true;
            //    multiFileId2.Visible = true;
            //    panelUploadMulti.Visible = true;
                
                
            //    inputFileId1.Visible = false;
            //    UpdatePanel1.Visible = false;
            //}
            //else //单个
            //{
            //    UpdatePanel1.Visible = true;
            //    panelUploadMulti.Visible = false;
            //}
            //TODO:查询字符串应该加密

            string upload_mode = Request.QueryString[null];
            if (upload_mode == null)
            {
                Utility.SiteError("缺失必须的上传模式参数!", Response);
            }
            else
            {
                ViewState["UPLOAD_MODE"] = upload_mode;
                #region 处理上传模式
                switch (upload_mode)
                {
                    case "docs":
                        {
                            #region 为了文档管理而上传所需要的各种参数信息
                            string dirid = Request.QueryString["dirid"];
                            if (String.IsNullOrEmpty(dirid) || dirid.Trim().Length == 0)
                            {
                                Utility.SiteError("缺失所必需的参数【目录编号】", Response);
                            }
                            else
                            {
                                ViewState["DIRID"] = dirid.Trim();
                            }
                            string dirname =Server.HtmlDecode(Request.QueryString["dirname"]);
                            if (String.IsNullOrEmpty(dirname) || dirname.Trim().Length == 0)
                            {
                                Utility.SiteError("缺失所必需的参数【目录名称】", Response);
                            }
                            else
                            {
                                ViewState["DIRNAME"] = dirname;
                            }


                            labelUploadContext.Text = String.Format("在目录【{0}】，编号【{1}】下添加文件：", dirname, dirid);

                            #endregion
                            break;
                        }
                    case "parameterfile":
                        {
                            #region 为了合同而上传参数文件

                            string report_id = Request.QueryString["report_id"];//获取合同ID号
                            if (String.IsNullOrEmpty(report_id) || report_id.Trim().Length == 0)
                            {
                                Utility.SiteError("缺失所必需的参数【合同编号】", Response);
                            }
                            else
                            {
                                ViewState["REPORT_ID"] = report_id;
                                MoContract mo = new MoContract();
                                mo.ReportId = report_id;
                                dacontract.GetEntityEx(ref mo);
                                labelUploadContext.Text = String.Format("为客户【{0}】合同【{1}】上传参数文件：",
                                    mo.CorpName, report_id);

                            }
                            #endregion
                            break;
                        }
                    case "notice":
                        {
                            #region 为通知上传附件
                            //给定通知的EID，给定通知标题，给定返回URL


                            string notice_id = Request.QueryString["id"];//获取合同ID号
                            if (String.IsNullOrEmpty(notice_id) || notice_id.Trim().Length == 0)
                            {
                                Utility.SiteError("缺失所必需的参数【通知编号】", Response);
                            }
                            else
                            {
                                ViewState["NOTICE_ID"] = notice_id;
                                MoNotice mo = new MoNotice();
                                mo.NoticeId = notice_id;
                                daNotice.GetEntityEx(ref mo);

                                labelUploadContext.Text = String.Format("为通知【{0}】【{1}】上传附件：",
                                    mo.NoticeId, mo.NoticeContent.Substring(0, (mo.NoticeContent.Length > 10) ? 10 : mo.NoticeContent.Length) + "...");
                            }
                            #endregion
                            break;
                        }
                    case "sample":
                        {
                            #region 为样品上传附件
                            //给定样品的EID，给定样品标题，给定返回URL                          
                            string sampleid = Request.QueryString["id"];
                            if (String.IsNullOrEmpty(sampleid) || sampleid.Trim().Length == 0)
                            {
                                Utility.SiteError("缺失所必需的参数【样品编号】", Response);
                            }
                            else
                            {
                                ViewState["SAMPLE_ID"] = sampleid;
                                MoSampleKept mo = new MoSampleKept();
                                mo.SamKepId = sampleid;
                                daSample.GetEntityEx(ref mo);
                                labelUploadContext.Text = String.Format("为样品【{0}】【{1}】上传附件：",
                                    mo.SamKepId, mo.SampleName.Substring(0, (mo.SampleName.Length > 10) ? 10 : mo.SampleName.Length) + "...");
                            }
                            #endregion
                            break;
                        }
                    case "testitem":
                        {
                            #region 为检验项上传附件
                            //给检验项的EID，给定返回URL


                            string templateid = Request.QueryString["id"];//获取检验项ID号
                            string type = Request.QueryString["type"];
                            if (String.IsNullOrEmpty(templateid) || templateid.Trim().Length == 0 || String.IsNullOrEmpty(type) || type.Trim().Length == 0)
                            {
                                Utility.SiteError("缺失所必需的参数【检验项编号或模板类型】", Response);
                            }
                            else
                            {
                                ViewState["TEMPLATE_ID"] = templateid;
                                ViewState["TEMPLATE_TYPE"] = type;
                                MoFileTemplate mot = new MoFileTemplate();
                                mot.FtId = templateid;
                                daTemplate.GetEntityEx(ref mot);
                                MoTestCatalog moc = new MoTestCatalog();
                                moc.TestCtgId = mot.ItemCode;
                                daCatalog.GetEntityEx(ref moc);

                                labelUploadContext.Text = String.Format("为检验项【{0}】【{1}】上传{2}模板：",
                                    moc.TestCtgId, moc.TestCtgName.Substring(0, (moc.TestCtgName.Length > 10) ? 10 : moc.TestCtgName.Length) + "...", type == "doc" ? "Word" : "Excel");
                            }
                            #endregion
                            break;

                        }
                    case "co_testitem_xls":
                        {
                            #region 为合同检验项上传XLS原始记录


                            string co_item_id = Request.QueryString["co_item_id"];
                            if (String.IsNullOrEmpty(co_item_id))
                            {
                                Utility.SiteError("缺失所必需的参数【合同检验项编号】", Response);
                            }
                            else
                            {
                                ViewState["CO_ITEM_ID"] = co_item_id;
                                DaCoTestItem dacti = DevFuture.Common.WorkContext.AppCtx.GetObject("DaCoTestItem") as DaCoTestItem;
                                MoCoTestItem mo = new MoCoTestItem();
                                mo.CoItemId = co_item_id;
                              
                                if (!dacti.GetEntityEx(ref mo))
                                {
                                    Utility.GlobalLog.ErrorFormat("给定的合同检验项{0}无效!", co_item_id);
                                    Utility.SiteError("给定的合同检验项无效:" + co_item_id);
                                }
                                else
                                {
                                    labelUploadContext.Text = String.Format("为合同{0}的检验项{1}{2}上传原始记录文件(Excel)",
                                        mo.ReportId, mo.CoItemId, mo.ItemTitle);
                                }
                            }
                            #endregion
                            break;
                        }
                    case "report":
                        {
                            #region 上传最终报告
                            string report_id = Request.QueryString["id"];
                            if (String.IsNullOrEmpty(report_id) || report_id.Trim().Length == 0)
                            {
                                Utility.SiteError("缺失所必需的参数【报告编号】", Response);
                            }
                            else
                            {
                                ViewState["REPORT_ID"] = report_id;
                                MoContract mo = new MoContract();
                                mo.ReportId = report_id;
                                dacontract.GetEntityEx(ref mo);
                                labelUploadContext.Text = String.Format("为报告【{0}】【{1}】上传检验报告：",
                                    mo.ReportId, mo.CorpName);
                            }

                            #endregion
                            break;
                        }
                    default:
                        {
                            Utility.SiteError("未知的文档上传请求", Response);
                            break;
                        }
                }
                #endregion
            }
        }
        
    }

    protected void btnUpload1_Click(object sender, EventArgs e)
    {
        //if (this.IsValid && inputFileId1.HasFile)
        //{
        //    inputFileId1.MoveTo(Path.Combine(Request.PhysicalApplicationPath + "temp\\", inputFileId1.FileName),
        //        MoveToOptions.Overwrite);
        //}

        if (this.IsValid && inputFileId1.HasFile)
        {
            string file_id = SequenceKeys.GenerateFileID();
            //写到本地时的全路径，用URL表达
            string localpath = System.IO.Path.Combine(SiteConfig.File_Repository_Location,
                file_id + System.IO.Path.GetExtension(inputFileId1.FileName));
            //inputFileId1.MoveTo(localpath, MoveToOptions.Overwrite);
            using (inputFileId1.FileContent)
            {
                using (System.IO.FileStream sw = new FileStream(localpath, FileMode.Create))
                {
                    Utility.CopyStream(inputFileId1.FileContent, sw);
                    sw.Close();
                }
                inputFileId1.FileContent.Close();
            }

            MoTfiles motfile = new MoTfiles();
            motfile.FileId = file_id;
            motfile.FileLength = inputFileId1.FileContent.Length;
            motfile.FileName = inputFileId1.FileName; //原始文件的名称，含扩展名，不含路径    
            motfile.FileUrl = Utility.GetUri4LocalFile(localpath);

            string upload_mode = ViewState["UPLOAD_MODE"].ToString();
            switch (upload_mode)
            {
                case "docs":
                    {
                        #region 为文档管理而上传
                        MoDirFile modf = new MoDirFile();
                        modf.DfId  = file_id;
                        modf.DfName = inputFileId1.FileName;
                        modf.DfFlag = "F";
                        modf.ParentDid = ViewState["DIRID"].ToString();
                        try
                        {
                            datfile.AddFileEx(modf, motfile);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!" + de.Message, Response);
                        }
                        #endregion
                        break;
                    }
                case "parameterfile":
                    {
                        #region 参数文件上传
                        MoSampleParameter mosp = new MoSampleParameter();
                        mosp.SampleId = SequenceKeys.GenerateSampleID();
                        mosp.ReportId = ViewState["REPORT_ID"].ToString();
                        mosp.RegDate = DateTime.Today;
                        mosp.RefParFile = file_id;

                        try
                        {
                            dasp.AddSampleParameterFile(motfile, mosp);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("为合同添加参数文件上传失败!", de);
                            Utility.SiteError("为合同添加参数文件上传失败!" + de.Message, Response);
                        }
                        break;
                        #endregion
                    }
                case "notice"://公告附件
                    {

                        MoRefFile modref = new MoRefFile();
                        modref.Eid = ViewState["NOTICE_ID"].ToString();
                        modref.FileId = motfile.FileId;
                        modref.RfId = SequenceKeys.GenerateReferFileID();
                        try
                        {
                            datfile.AddFileEx(motfile, modref);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!", Response);
                        }
                        break;
                    }
                case "sample"://样品附件
                    {
                        MoRefFile modref = new MoRefFile();
                        modref.Eid = ViewState["SAMPLE_ID"].ToString();
                        modref.FileId = motfile.FileId;
                        modref.RfId = SequenceKeys.GenerateReferFileID();
                        try
                        {
                            datfile.AddFileEx(motfile, modref);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!", Response);
                        }
                        break;

                    }
                case "testitem"://检验项
                    {
                        MoRefFile modref = new MoRefFile();
                        modref.Eid = ViewState["TEMPLATE_ID"].ToString();
                        modref.FileId = motfile.FileId;
                        modref.RfId = SequenceKeys.GenerateReferFileID();
                        try
                        {
                            if (ViewState["TEMPLATE_TYPE"].ToString() == "doc")
                            {
                                daItem.AddTemplateDoc(motfile, modref);
                            }
                            else
                            {
                                daItem.AddTemplateXls(motfile, modref);
                            }
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加单个文件失败!", de);
                            Utility.SiteError("添加单个文件失败!", Response);
                        }
                        break;

                    }
                case "co_testitem_xls"://合同检验项，上传原始记录文件
                    {

                        //Note:为合同检验项上传原始记录时，实际并不知道他使用的是那个原始记录模板，因此，我们要求原始记录模板可以自描述(2009-5-11)
                        //Note:假定Excel文件的sheet2的单元格B1记录着此文件的模板编码；这个编码在Job分析模板时，默认的写在了这个B1单元格，用户不可更改；
                        MoTestRecord mo = new MoTestRecord();
                        mo.TrId = SequenceKeys.GenerateTestRecordID();//主键
                        mo.CoItemId = ViewState["CO_ITEM_ID"].ToString();
                        mo.TrUrl = file_id;//原始记录文件
                        DaTestRecord datr = DevFuture.Common.WorkContext.AppCtx.GetObject("DaTestRecord") as DaTestRecord;

                        try
                        {
                            datr.AddTestRecordFile(motfile, mo);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加原始记录文件失败!", de);
                            Utility.SiteError("添加原始记录文件失败!", Response);
                        }
                        break;

                    }
                case "report":
                    {
                        #region 上传最终报告
                        string report_id = ViewState["REPORT_ID"].ToString();
                        try
                        {
                           
                            dacontract.UploadContractReport(motfile, report_id,User.Identity.Name);
                        }
                        catch (DalException de)
                        {
                            Utility.GlobalLog.Error("添加报告文件失败!", de);
                            Utility.SiteError("添加报告文件失败!", Response);
                        }
                        #endregion
                        break;
                    }
                default: break;
            }
            inputFileId1.Dispose();
        }
    }

    /// <summary>
    /// 一个实体关联多个文档时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUploadMulti_Click(object sender, EventArgs e)
    {
        if (multiFileId2.Files.Length > 0)
        {
            List<MoTfiles> fileList = new List<MoTfiles>(multiFileId2.Files.Length);
            List<MoDirFile> dfList = new List<MoDirFile>(multiFileId2.Files.Length);

            uploadPre.InnerText += "批次上传 " + multiFileId2.Files.Length + " 文件:\n";
            foreach (UploadedFile file in multiFileId2.Files)
            {
                string file_id = SequenceKeys.GenerateFileID();
                //写到本地时的全路径，用URL表达
                string localpath = System.IO.Path.Combine(SiteConfig.File_Repository_Location,
                    file_id + System.IO.Path.GetExtension(file.FileName));
                try
                {
                    using (file.InputStream)
                    {
                        using (FileStream fs = new FileStream(localpath, FileMode.Create))
                        {
                            Utility.CopyStream(file.InputStream, fs);
                            fs.Flush();
                        }
                        file.InputStream.Close();
                    }
                    //file.MoveTo(localpath, MoveToOptions.Overwrite);
                }
                catch (SystemException se)
                {
                    Utility.GlobalLog.Error("上传文件失败！", se);
                    uploadPre.InnerText += Environment.NewLine + String.Format("上传文件【{0}】失败！", file.FileName) + Environment.NewLine + se.Message;
                    break;
                }

                MoDirFile modf = new MoDirFile();
                modf.DfId  = file_id;
                modf.DfName = file.FileName;
                modf.DfFlag = "F";
                //Note:批次上传只针对文档管理
                modf.ParentDid = ViewState["DIRID"].ToString();

                MoTfiles motfile = new MoTfiles();
                motfile.FileId = file_id;
                motfile.FileLength = file.ContentLength;
                motfile.FileName = file.FileName; //原始文件的名称，含扩展名，不含路径    
                motfile.FileUrl = Utility.GetUri4LocalFile(localpath);

                fileList.Add(motfile);
                dfList.Add(modf);
                uploadPre.InnerText += file.FileName + "\n";
            }
            try
            {
                datfile.AddFileEx(dfList, fileList);
            }
            catch (DalException de)
            {
                Utility.GlobalLog.Error("批量添加文件失败!", de);
                Utility.SiteError("批量添加文件失败!" + de.Message, Response);
            }



        }
    }
    //单击了返回按钮
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        string upload_mode = ViewState["UPLOAD_MODE"].ToString();
        string return_url = String.Empty;
        switch (upload_mode)
        {
            case "docs"://返回至文档查看页面
                {
                    return_url = String.Format("docs.aspx?dir_id={0}", ViewState["DIRID"]);
                    break;
                }
            case "parameterfile"://返回至合同查看页面
                {
                    return_url = String.Format("CreateContract.aspx?reportid={0}", ViewState["REPORT_ID"]);
                    break;
                }
            case "notice"://公告
                {
                    return_url = String.Format("notice.aspx?edit&noticeid={0}", ViewState["NOTICE_ID"]);
                    break;
                }
            case "sample": //样品
                {
                    return_url = String.Format("samplekept.aspx?edit&sampleid={0}", ViewState["SAMPLE_ID"]);
                    break;
                }
            case "testitem": //检验项
                {
                    return_url = String.Format("TestItem.aspx");
                    break;
                }
            default:
                {
                    return_url = "/";
                    break;
                }
        }
        Response.Redirect(return_url);

    }
}
